//
//  PersonageAmendVC.m
//  StandardizedProduct
//
//  Created by 洛水寒 on 16/7/25.
//  Copyright © 2016年 ym. All rights reserved.
//

#import "PersonageAmendVC.h"

#import "PersonageAmendCell.h"//TableViewCell

#import "NickNameVC.h"//修改昵称Controller
#import "AccountSecurityViewController.h"//账户安全Controller

#import "JHSelector.h"//日期选择器

@interface PersonageAmendVC ()<UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>


@property (nonatomic, strong) UITableView *tableView;

@end

@implementation PersonageAmendVC
{
    
    NSArray *_personalArray;
    
    UIImagePickerController *_picker;
    
    NSString *_nickName;
    NSString *_sex;
    NSString *_birth;
    NSString *_realName;
    
    NSUserDefaults *_defaluts;
}

 static NSString *const PersonageAmendCellID1 = @"PersonageAmendCell1";
 static NSString *const PersonageAmendCellID2 = @"PersonageAmendCell2";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _defaluts = [NSUserDefaults standardUserDefaults];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;//跳过64
    self.tableView.backgroundColor = BackgroundCOLOR;
    
    _personalArray = @[@"头像",@"用户名",@"昵称",@"性别",@"出生日期",@"地址管理",@"实名认证",@"账户安全"];
    
    [self setNav];
    
    if (_model) {
        _nickName = _model.Nick;
        if ([_model.Sex isEqualToString:@"0"]) {
            _sex = @"男";
        }else _sex = @"女";
        _birth = _model.Birthday;
        _realName = _model.Name;
    }
    
}

- (void)setNav{
    self.title = @"账户管理";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存"  style:UIBarButtonItemStyleDone target:self action:@selector(saveBtnClick)];
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
    back.title = @"";
    self.navigationItem.backBarButtonItem = back;
    
    
}

//保存
- (void)saveBtnClick{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否确认保存修改?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
    
    UIAlertAction *save = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"保存");
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:save];
    
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark === TableViewDelegate ===
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
         return 70;
    }
    return 50;
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
//section数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _personalArray.count;
}
//重用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PersonageAmendCell *cell = nil;

     NSArray *xibArray = [[NSBundle mainBundle] loadNibNamed:@"PersonageAmendCell" owner:nil options:nil];

    if (indexPath.section == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:PersonageAmendCellID1];
        if (cell == nil){
            cell = xibArray[0];
        }
    }else{
        cell = [tableView dequeueReusableCellWithIdentifier:PersonageAmendCellID2];
        if (cell == nil){
            cell = xibArray[1];
        }
       
    }
    cell.headImg.tag = 100;
    cell.headLab.text = _personalArray[indexPath.section];
    cell.titleLab.text = _personalArray[indexPath.section];
    if (indexPath.section != 1) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//标示符
    }
    
    
    switch (indexPath.section) {
        case 1:
            cell.contentLab.textColor = [UIColor lightGrayColor];
            break;
        case 2:
            cell.contentLab.text = _nickName;
            break;
        case 3:
            cell.contentLab.text = _sex;
            break;
        case 4:
            cell.contentLab.text = _birth;
            break;
        case 6:
            cell.contentLab.text = _realName;
            break;
        default:
            break;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //[cell writeCellMessage];
    return cell;
}
//section高
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 4;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 4)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
//点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    switch (indexPath.section) {
        case 0:
        {//头像
//            [self amendHeadPortrait];
        }
            break;
        case 1:
        {
            //用户名
        }
            break;
        case 2:
        {//昵称
            [self amendNickname];
        }
            break;
        case 3:
        {//修改性别
            [self amendSex];
        }
            break;
        case 4:
        {//修改出生日期
            [self amendDate];
        }
            break;
        case 5:
        {
            
        }
            break;
        case 6:
        {
            
        }
            break;
        case 7:
        {
            [self accountSafety];
        }
            break;
            
        default:
            break;
    }
}
//修改头像
-(void)amendHeadPortrait
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [cancel setValue:[UIColor blackColor] forKey:@"titleTextColor"];
    [alert addAction:cancel];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"从相册选择" style:0 handler:^(UIAlertAction * _Nonnull action) {
        //从现有的照片库中选择图像
        if([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypePhotoLibrary)]) {
            _picker = [[UIImagePickerController alloc] init];
            
            [[UINavigationBar appearance] setBarTintColor:APPCOLOR];
            
            [_picker setSourceType:(UIImagePickerControllerSourceTypePhotoLibrary)]; //资源类型为图片库
            [_picker setAllowsEditing:YES]; //设置选择后的图片可被编辑
            [_picker setDelegate:self];
            [self presentViewController:_picker animated:YES completion:^{ }];
        }
    }];
    [camera setValue:[UIColor blackColor] forKey:@"titleTextColor"];
    [alert addAction:camera];
    
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //使用内置的照相机拍摄图片
        if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) { //判断是否有摄像头
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            [picker setSourceType:(UIImagePickerControllerSourceTypeCamera)]; //资源类型为照相机
            [picker setAllowsEditing:YES]; //设置拍照后的图片可被编辑
            [picker setDelegate:self];
            [self presentViewController:picker animated:YES completion:^{
            }];
        }
    }];
    
    [album setValue:[UIColor blackColor] forKey:@"titleTextColor"];
    [alert addAction:album];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}
//修改昵称
-(void)amendNickname
{
    NickNameVC *nick = [[NickNameVC alloc] init];
    nick.nick = _nickName;
    [self.navigationController pushViewController:nick animated:YES];
}
//修改性别
- (void)amendSex
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [cancel setValue:[UIColor blackColor] forKey:@"titleTextColor"];
    [alert addAction:cancel];
    
    UIAlertAction *boy = [UIAlertAction actionWithTitle:@"男" style:0 handler:^(UIAlertAction * _Nonnull action) {
        _sex = @"男";
        [_tableView reloadData];
    }];
    [boy setValue:[UIColor blackColor] forKey:@"titleTextColor"];
    [alert addAction:boy];
    
    UIAlertAction *girl = [UIAlertAction actionWithTitle:@"女" style:0 handler:^(UIAlertAction * _Nonnull action) {
        _sex = @"女";
        [_tableView reloadData];
    }];
    [girl setValue:[UIColor blackColor] forKey:@"titleTextColor"];
    [alert addAction:girl];
    
    [self presentViewController:alert animated:YES completion:nil];
}
//修改日期
- (void)amendDate
{
    JHSelector *selector = [[JHSelector alloc]init];
    [selector.btn setTitle:@"取消" forState:UIControlStateNormal];
    [selector.btn2 setTitle:@"确定" forState:UIControlStateNormal];
    
    selector.clickedBtnIndexBlock = ^(NSInteger index)
    {
        if (index == 1){
            _birth = selector.dateString;
            [_tableView reloadData];
        }
    };
    [selector show];

}
//地址管理
- (void)amendAddress
{
    

}
//实名认证
- (void)trueApprove
{
    
}
//账户安全
- (void)accountSafety
{
    AccountSecurityViewController *accountSecurity = [[AccountSecurityViewController alloc] init];
    accountSecurity.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:accountSecurity animated:YES];
}



#pragma mark - UIImagePickerControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [navigationController.navigationBar setBarStyle:(UIBarStyleBlackTranslucent)];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    [picker dismissViewControllerAnimated:YES completion:^{ }]; //关闭摄像头或用户相册
    
    //DBLOG(@"加载图片中...");
    UIGraphicsBeginImageContext(image.size);
    [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    
    UIGraphicsEndImageContext();
    NSData *data= UIImageJPEGRepresentation(newImage, 0.1);
    NSString *str = [data base64Encoding];
    
    dispatch_async(dispatch_get_main_queue(), ^{
      //  _headImg.image = newImage;
       // _imgString = str;
        //[self saveImage:newImage WithName:@"userAvatar"];
    });
}

#pragma mark === 会员修改 ===
- (void)changeInfo{
    NSString *sexxx;
    if ([_sex isEqualToString:@"男"]) {
        sexxx = @"0";
    }else sexxx = @"1";
    
    
    NSDictionary *para = @{
                           @"UserName"     :  @"maroonnnnn",
                           @"Nick"         :  _nickName,
                           @"Sex"          :  sexxx,
                           @"Birthday"     :  _birth,
//                           @"Mobile"       :  @"15757855404",
//                           @"ProvinceName" :  @"浙江省",
//                           @"CityName"     :  @"海宁市",
                           @"RowStatus"    :  @"UPDATE",
                           @"Id"           :  [_defaluts objectForKey:@"Id"]
                           };
    
    NSString *paraString = [NetWorkManager dictionaryToJson:para];
    
    NSDictionary *paraments = @{
                                @"command"   :  @"onEdit",
                                @"tableId"   :  @"294",
                                @"params"    :  paraString,
                                @"Id"        :  @""
                                };
    
    [NetWorkManager requestWithMethodName:@"12082/api/Rest/RestProcess?" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"会员修改  :  %@", object);
        NSLog(@"%@", object[@"Message"]);
        if ([object[@"Code"] isEqualToString:@"0"]) {
            [EBUtility prompt:@"信息修改成功" with:self];
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"会员修改网络请求失败  : %@", error);
    } progress:nil];
}


- (UITableView *)tableView{
    if (!_tableView) {
        _tableView= [[UITableView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        _tableView.tableFooterView = [[UIView alloc]init];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

@end
